package Other.alibaba;

/**
 * @Classname MyBlockQueue
 * @Description TODO
 * @Date 2021/6/27 21:12
 * @Created by ASUS
 */
public class MyBlockQueue {

    public Object[] elements;


    public int head;
    public int tail;
    public int size;


    public MyBlockQueue(int initialCapacity) {
        this.elements = new Object[initialCapacity];
        this.head = 0;
        this.tail = 0;
        this.size =0;
    }

    public MyBlockQueue() {
        new MyBlockQueue(16);
    }

    private void enterQueue(Object element) {
        while (true) {
            synchronized (this) {
                if (size != elements.length) {
                    this.elements[tail] = element;
                    this.tail ++;
                    if (this.tail == elements.length) this.tail = 0;
                    this.size++;
                    return;
                }
            }
        }
    }

    private Object outQueue() throws InterruptedException {
        while (true) {
            synchronized (this) {
                if (size != 0) {
                    Object out = elements[this.head];
                    elements[this.head] = null;
                    this.head ++;
                    if (this.head == elements.length) this.head = 0;
                    this.size--;
                    return out;
                }
            }
            Thread.sleep(10000);
        }
    }


    public Object take() throws InterruptedException {
        return outQueue();
    }

    public void put(Object element) throws InterruptedException {
        enterQueue(element);
    }

    public boolean isEmpty() {
        return size == 0;
    }



}
